<template>
  <StyleTransformSkeleton v-if="isLoading" />
  <section v-if="!isLoading && styleItems.length > 0" class="style-transform-section">
    <div class="section-title">
      <h2>STYLE TRANSFORMATIONS</h2>
      <div class="divider"></div>
    </div>

    <div class="style-grid-container">
      <div class="style-grid">
        <div v-for="(item, index) in styleItems" :key="index" class="style-item">
          <a :href="item.link" class="style-link">
            <div class="image-wrapper">
              <!-- <img :src="item.src" :alt="item.caption" class="style-image"> -->
              <VideoPlayer :videoSrc="item.video || ''" :autoplay="true" :muted="true" :loop="true" :showControls="true"
                :showPlayButton="true" />
              <div class="overlay">
                <div class="shop-button" @click.prevent="handleClick(item)">VIEW THE MATCHING</div>
              </div>
            </div>
            <div class="creator-info">
              <span class="creator-tag" @click.prevent="handleClick(item)">@{{ item.title }}</span>
            </div>
          </a>
        </div>
      </div>
    </div>

    <!-- 商品弹窗 -->
    <div class="matching-popup" v-if="showPopup" @click="closePopup">
      <div class="popup-content" @click.stop>
        <div class="popup-header">
          <h3>Shop The Look</h3>
          <button class="close-btn" @click="closePopup">
            <span class="close-icon">×</span>
          </button>
        </div>

        <div class="popup-body">
          <!-- 左侧视频区域 -->
          <div class="popup-video">
            <VideoPlayer v-if="currentItem" style="width: 100%; max-height: 630px; object-fit: cover;"
              :videoSrc="currentItem.video || ''" :autoplay="true" :muted="true" :loop="true" :showControls="true"
              :showPlayButton="true" />
          </div>

          <!-- 右侧商品列表 -->
          <div class="matching-products">
            <div class="product-item" v-for="(product, index) in currentItem?.shop_goods" :key="index">
              <div class="product-image">
                <img v-if="product.images && product.images.length > 0" :src="product.images[0]" :alt="product.name">
              </div>
              <div class="product-info">
                <h4 class="product-title">{{ product.name }}</h4>
                <p class="product-price">{{ currencyStore.currentCurrency.unit }}{{
                  proxy?.$ConvertPrice(product.max_price) }}<span class="zk-price">{{ currencyStore.currentCurrency.unit }} {{
                    proxy?.$ConvertPrice(product.max_origin_price) }}</span></p>
                <div class="product-actions">
                  <button class="quick-add-btn" @click="addToCart(product)">QUICK ADD</button>
                  <a :href="`/product/${product.url}.html`" class="view-details">View Full Details</a>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </section>

  <a-modal v-model:open="open" width="1260px" title="Product Details" :footer="null">
    <ProductDetail.default v-if="open && goodId" :goodId="goodId" @buy="handleBuy" />
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, onMounted, getCurrentInstance } from 'vue';
import { useRouter } from 'vue-router';
import VideoPlayer from '../../../components/VideoPlayer.vue';
import StyleTransformSkeleton from './StyleTransformSkeleton.vue'; // 引入骨架屏组件
import { message } from 'ant-design-vue';
import * as ProductDetail from '@/components/ProductDetail.vue';
import { getLookList } from '@/api';
import { useCurrencyStore } from '@/store';

// 修复proxy类型错误
const instance = getCurrentInstance();
// 使用类型断言来避免TypeScript错误
const proxy = instance ? (instance as any).proxy : null;
const currencyStore = useCurrencyStore();

const router = useRouter();
let isLoading = ref(true); // 新增加载状态

// 产品数据结构
interface Product {
  title: string;
  price: number;
  image: string;
  detailUrl: string;
  id: string;
  // 以下为 StyleItem.shop_goods[x] 内的属性，确保类型一致
  name?: string;
  images?: string[];
  max_price?: number;
  max_origin_price?: number;
  url?: string;
}

// 定义风格项数据结构
interface StyleItem {
  src?: string; // 改为可选，因为数据源是item.video
  video?: string; // 添加video属性
  caption?: string; // 改为可选
  creator?: string; // 改为可选
  link?: string;    // 改为可选
  products?: Product[]; // 改为可选
  title?: string; // 数据源已有
  shop_goods?: Product[]; // 添加此属性以匹配模板中的currentItem?.shop_goods
  id?: number; // 确保id存在，因为addToCart中用到了
}

// 弹窗状态
const showPopup = ref(false);
const currentItem = ref<StyleItem | null>(null);

// 风格转变数据
const styleItems = ref<StyleItem[]>([]);

// 获取风格转变数据
const getStyleTransformData = async () => {
  isLoading.value = true;
  try {
    styleItems.value = (window as any).__INITIAL_INDEX__.homeVideo
    // const res = await getLookList({
    //   page: 1,
    //   page_size: 100,
    //   type: '2' // 1-图片，2-视频
    // });
    // console.log(res);
    // styleItems.value = res.data.data;
  } catch (error) {
    console.error("Failed to fetch style transformations:", error);
    // 在这里可以添加错误处理，例如显示一个错误消息
  } finally {
    isLoading.value = false;
  }
}

onMounted(() => {
  getStyleTransformData();
});

// 点击风格转变弹窗
const handleClick = (item: StyleItem) => {
  currentItem.value = item;
  showPopup.value = true;
  // 阻止body滚动
  document.body.style.overflow = 'hidden';
}

// 关闭弹窗
const closePopup = () => {
  showPopup.value = false;
  // 恢复body滚动
  document.body.style.overflow = '';
}


const open = ref<boolean>(false);
// 修改goodId类型为string，允许null
const goodId = ref<string | null>(null);
// 添加到购物车
const addToCart = (product: Product) => {
  console.log('Added to cart:', product);
  if (product.id === undefined) {
      console.error("Product ID is undefined. Cannot add to cart.");
      message.error("Cannot add product to cart: Product ID is missing.");
      return;
  }
  open.value = true;
  goodId.value = String(product.id); // 将数字ID转换为字符串
}

const gotoDetail = (product: Product) => {
  console.log('Go to detail:', product);
  if (product.id === undefined) {
    console.error("Product ID is undefined. Cannot go to detail.");
    message.error("Cannot view product details: Product ID is missing.");
    return;
  }
  router.push({
    path: '/details',
    query: {
      id: product.id
    }
  });
}

const handleBuy = (product: any) => {
  // console.log('Buy product:', product);
  // message.success('The product has been successfully added to the cart');
  open.value = false;
};
</script>

<style scoped lang="scss">
.style-transform-section {
  // padding: 60px 0;
  margin-top: 60px;
  background-color: #fff;
  // margin-bottom: 60px;
  margin-bottom: 0;
  position: relative;
}

.section-title {
  text-align: center;
  margin-bottom: 40px;

  h2 {
    font-size: 28px;
    font-weight: 500;
    letter-spacing: 2px;
    margin-bottom: 15px;
    color: #000;
  }

  .divider {
    width: 50px;
    height: 2px;
    background-color: #000;
    margin: 0 auto;
  }
}

.style-grid-container {
  // max-width: 1400px;
  margin: 0 auto;
  padding: 0 20px;
}

.style-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
}

.style-item {
  position: relative;
  overflow: hidden;

  .style-link {
    display: block;
    text-decoration: none;
    color: inherit;
  }

  .image-wrapper {
    position: relative;
    overflow: hidden;
    aspect-ratio: 3 / 4;
  }

  .style-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.5s ease;
  }

  &:hover .style-image {
    transform: scale(1.05);
  }

  .overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.3);
    display: flex;
    justify-content: center;
    align-items: center;
    opacity: 0;
    transition: opacity 0.3s ease;
  }

  &:hover .overlay {
    opacity: 1;
  }

  .shop-button {
    padding: 12px 30px;
    background-color: #fff;
    color: #000;
    font-size: 14px;
    font-weight: 500;
    letter-spacing: 1px;
    transform: translateY(20px);
    transition: transform 0.4s ease, background-color 0.3s ease;
    cursor: pointer;
  }

  &:hover .shop-button {
    transform: translateY(0);
  }

  .creator-info {
    padding: 15px 0;
    text-align: center;
  }

  .creator-tag {
    font-size: 14px;
    color: #666;
    font-weight: 400;

    &:hover {
      text-decoration: underline;
    }
  }
}

/* 弹窗样式 */
.matching-popup {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.popup-content {
  width: 95%;
  max-width: 900px;
  max-height: 90vh;
  background-color: #fff;
  border-radius: 0;
  overflow-y: auto;
  position: relative;
  padding: 40px 0;
  padding-top: 0;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  // border-bottom: 1px solid #eee;

  h3 {
    font-size: 20px;
    font-weight: 500;
    margin: 0;
  }

  .close-btn {
    background: none;
    border: none;
    font-size: 24px;
    cursor: pointer;
    padding: 0;
    line-height: 1;
    color: #888;

    &:hover {
      color: #000;
    }
  }
}

.popup-body {
  display: flex;
  flex-direction: row;
}

.popup-video {
  flex: 0.9;
  padding: 20px;
  // border-right: 1px solid #eee;
  min-height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.matching-products {
  flex: 1;
  padding: 0 20px;
  max-height: 600px;
  overflow-x: hidden;
  overflow-y: auto;
}

.product-item {
  display: flex;
  padding: 20px;
  // border-bottom: 1px solid #eee;

  &:last-child {
    border-bottom: none;
  }
}

.product-image {
  width: 130px;
  flex-shrink: 0;
  margin-right: 20px;

  img {
    width: 100%;
    height: auto;
    display: block;
  }
}

.product-info {
  flex-grow: 1;
  width: 65%;
}

.product-title {
  font-size: 14px;
  line-height: 20px;
  -webkit-line-clamp: 1;
  margin-top: 0;
  font-weight: 400;
  //溢出省略号
  width: 100%;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  cursor: pointer;

  &:hover {
    text-decoration: underline;
  }
}

.product-price {
  font-size: 16px;
  font-weight: 500;
  margin: 0 0 15px;
  color: #000;
  width: 100%;
  .zk-price{
    text-decoration: line-through;
    margin-left: 6px;
    color: #999;
    font-weight: normal;
    font-size: 90%;
  }
}

.product-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.quick-add-btn {
  background-color: #fff;
  border: 1px solid #000;
  color: #000;
  padding: 8px 15px;
  font-size: 14px;
  cursor: pointer;
  max-width: 160px;
  text-align: center;
  font-weight: 500;
  transition: background-color 0.3s, color 0.3s;

  &:hover {
    background-color: #000;
    color: #fff;
  }
}

.view-details {
  text-align: left;
  color: #232323;
  text-decoration: none;
  font-size: 14px;
  padding: 5px 0;
  padding-bottom: 1px;
  width: 112px;
  border-bottom: 1px solid #232323;
  margin-bottom: 10px;

  &:hover {
    // font-weight: 600;
  }
}

// 响应式样式
@media (max-width: 992px) {
  .style-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
  }

  .section-title h2 {
    font-size: 24px;
  }

  .style-transform-section {
    padding: 40px 0;
  }
}

@media (max-width: 768px) {
  .popup-content {
    width: 100%;
    max-width: 100%;
    height: 100%;
    max-height: 100%;
    border-radius: 0;
  }

  .popup-body {
    flex-direction: column;
  }

  .popup-video {
    width: 100%;
    border-right: none;
    border-bottom: 1px solid #eee;
    padding: 15px;
    min-height: auto;
    max-height: 40vh;
  }

  .matching-products {
    width: 100%;
    max-height: none;
  }

  .product-item {
    padding: 15px;
  }

  .product-image {
    width: 80px;
    margin-right: 15px;
  }

  .product-title,
  .product-price {
    font-size: 14px;
  }

  .quick-add-btn {
    padding: 8px 12px;
    font-size: 13px;
  }

  .view-details {
    font-size: 13px;
  }
}

@media (max-width: 576px) {
  .style-grid {
    grid-template-columns: 1fr;
    gap: 20px;
  }

  .style-item {
    max-width: 400px;
    margin: 0 auto;
  }

  .section-title {
    margin-bottom: 30px;

    h2 {
      font-size: 20px;
      margin-bottom: 10px;
    }
  }

  .style-transform-section {
    padding: 30px 0;
    margin-bottom: 40px;
  }

  .shop-button {
    padding: 10px 16px;
    font-size: 12px;
  }

  .creator-tag {
    font-size: 12px;
  }

  .popup-header h3 {
    font-size: 18px;
  }

  .product-item {
    flex-direction: column;
  }

  .product-image {
    width: 100%;
    margin-right: 0;
    margin-bottom: 15px;
  }
}

/* 触摸设备支持 */
@media (hover: none) {
  .style-item .overlay {
    background-color: rgba(0, 0, 0, 0.2);
    opacity: 1;
  }

  .style-item .shop-button {
    transform: translateY(0);
    background-color: rgba(255, 255, 255, 0.9);
  }
}
</style>